<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>嵌入式加载示例</title>
  <style>
      html, body {
          margin: 0;
          padding: 0;
          width: 100%;
          height: 100%;
      }

      .url {
          position: fixed;
          display: block;
          left: 10px;
          top: 10px;
      }

      .url input {
          width: 500px;
      }

      iframe {
          border: 0;
          padding: 0;
          margin: 0;
          min-height: 100vh;
          width: 100%;
      }
  </style>
</head>
<body>
<div class="url">
  <select value="./word.docx" onchange="context.url = this.value" placeholder="请输入测试url">
    <option value="./word.docx">测试word文档</option>
    <option value="./excel.xlsx">测试Excel文档</option>
    <option value="./ppt.pptx">测试PPT文档</option>
    <option value="./pic.png">测试PNG图片</option>
    <option value="./pdf.pdf">测试PDF文档</option>
    <option value="./video.mp4">测试视频</option>
  </select>
  <button onclick="loadFromUrl()">预览</button>
</div>
<script>
  var context = {
    // 查看器的源，当前示例为在线，本地测试请改为 http://localhost:8900
    origin: 'http://viewer.flyfish.group',
    // 目标frame
    frame: null,
    // 文件url
    url: './word.docx'
  };
  function appendFrame(src) {
    if (context.frame) {
      document.body.removeChild(context.frame);
    }
    // 构建frame
    var frame = context.frame = document.createElement('iframe');
    frame.src = src;
    frame.style = ''
    return document.body.appendChild(frame)
  }

  function loadFromUrl() {
    // 要预览的文件地址
    var url = context.url;
    // 取得文件名
    var filename = url.substr(url.lastIndexOf('/') + 1);
    // 拼接iframe请求url
    var src = context.origin + '?name=' + encodeURIComponent(filename) + '&from=' + encodeURIComponent(location.origin);
    // 拼接frame
    var frame = appendFrame(src);
    // 绑定事件
    frame.onload = () => {
      fetch(url, { mode: "no-cors" }).then(function (res) {
        return res.blob();
      }).then(function (data) {
        if (!data) {
          console.error('文件下载失败');
        }
        console.log(data)
        frame.contentWindow.postMessage(data, context.origin);
      })
    }
  }

  loadFromUrl();
</script>
</body>
</html>
